package threadTest.myCompletableFuture;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:completable catch异常
 * 2024/08/20
 *
 * @author ZhangYi
 */
public class CompletableFutureCatchException {


	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
				Runtime.getRuntime().availableProcessors(),
				2,
				TimeUnit.NANOSECONDS,
				new ArrayBlockingQueue<>(10),
				new ThreadPoolExecutor.CallerRunsPolicy());

		CompletableFuture<String> userCmpletableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(1 / 0);
			return new UserService().getUserInfo();
		});

		CompletableFuture<String> userRoleCompletableFuture = CompletableFuture.supplyAsync(() -> {
			return new UserRoleService().getUserRole("1");
		});

		userCmpletableFuture
				.whenComplete((result,ex)->{
					if(ex!=null){
						System.out.println("异常信息:"+ex.getMessage());
					}else{
						System.out.println("正常信息:"+result);
					}
				});

		CompletableFuture<String> exceptionally = userCmpletableFuture.exceptionally((ex) -> {
			if (ex != null) {
				System.out.println(ex.getMessage());
			}
			return "";
		});

		//
		try {
			CompletableFuture.allOf(userCmpletableFuture,userRoleCompletableFuture).join();
		} catch (Exception e) {

			throw new RuntimeException(e);
		}

	}
}
